<?php declare(strict_types=1);

namespace Zyucv7\Core\Web\Response;

use Zyucv7\Core\Web\Response;
use Zyucv7\Core\Web\Exceptions\ResponseException;

/**
 * 下载 响应类
 * 
 * 提供便捷的方法来生成和发送下载格式的 HTTP 响应
 */

class DownloadResponse {

    /**
     * 设置文件下载响应
     * 
     * @param string $filePath 文件路径
     * @param string $filename 下载的文件名
     * @param string $mimeType MIME类型
     * @return self
     * @throws InvalidArgumentException 如果文件不存在或无法读取
     */
    public static function send(string $filePath, string $filename = '', string $mimeType = ''): void
    {
        if (!file_exists($filePath) || !is_readable($filePath)) {
            throw ResponseException::InvalidArgument("File does not exist or is not readable: {$filePath}");
        }
        
        if (empty($filename)) {
            $filename = basename($filePath);
        }
        
        if (empty($mimeType)) {
            $mimeType = mime_content_type($filePath) ?: 'application/octet-stream';
        }
        
        $resp = Response::instance();
        $resp->addHeader('Content-Type', $mimeType);
        $resp->addHeader('Content-Disposition', "attachment; filename=\"{$filename}\"");
        $resp->addHeader('Content-Length', (string)filesize($filePath));
        $resp->addHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
        $resp->addHeader('Pragma', 'no-cache');
        $resp->addHeader('Expires', '0');
        $resp->setContent(file_get_contents($filePath));
        $resp->send();
    }
    
}